package utils

import (
	"errors"
	"fmt"
	"net/http"
	"net/url"
	"strings"

	"github.com/astaxie/beego"
)

var (
	PARSE_API = ""
)

func init() {
	PARSE_API = beego.AppConfig.DefaultString("parse_api", `http://baowen.xhh.com:47498`)
	beego.Info(PARSE_API)
}

func GetRealAddr(addr string) string {
	if !strings.Contains(addr, `marquess.test`) {
		return addr
	}
	if strings.HasPrefix(addr, "http://pic.cdn.xhh.com/") {
		return strings.Replace(addr, "http://pic.cdn.xhh.com/", "", 1)
	}
	req := Get(addr)
	resp, err := req.SetCheckRedirect(func(req *http.Request, via []*http.Request) error {
		return http.ErrUseLastResponse
	}).Response()
	if err != nil {
		beego.Error(err)
		return ""
	}
	return resp.Header.Get("Location")
}

type PlayUrl struct {
	PlayUrl string `json:"playurl"`
}

func GetVideoRealAddr(addr string) (string, error) {
	res, err := Get(addr).Response()
	if err != nil {
		return "", err
	}
	contentType := res.Header.Get("Content-Type")
	if strings.Contains(contentType, "html") {
		api := fmt.Sprintf(`%s/video/feed?url=%s`, PARSE_API, url.QueryEscape(addr))
		playUrl := PlayUrl{}
		if err := Get(api).ToJSON(&playUrl); err != nil {
			return "", err
		}
		if len(playUrl.PlayUrl) == 0 {
			return "", errors.New("解析真实地址失败")
		}
		return playUrl.PlayUrl, nil
	}

	realAddr := GetRealAddr(addr)
	return realAddr, nil
}
